package com.i2bt.app;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public abstract class BaseFragment extends Fragment implements OnClickListener, 
OnItemClickListener {
	
	protected static Context context;
	
	protected BaseActivity activity;
	
	protected ListView listView;		//公用的列表视图
	
	protected Menu menu; // 公用菜单
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 允许使用fragment来管理菜单
		setHasOptionsMenu(true);
		
		activity = (BaseActivity) getActivity();
		context = activity.getBaseContext();
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}
	
	/**
	 * 初始化视图
	 */
	abstract protected void initView();
	
	/**
	 * 调用业务逻辑处理
	 */
	abstract protected void logic();
	
	/**
	 * 点击actionbar的回退按钮调用的方法
	 */
	public abstract void backHomeOperate();
	
	/**
	 * 进入指定活动并携带数据包
	 * @param cls
	 * @param bundle 数据包
	 */
	public void goActivity(Class<?> cls, Bundle bundle) {
		Intent intent = new Intent(activity, cls);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		startActivity(intent);
	}
	
	/**
	 * 进入指定活动类
	 * 
	 * @param cls
	 *            将打开的活动类
	 */
	public void goActivity(Class<?> cls) {
		this.goActivity(cls, null);
	}
	
	/**
	 * 携带参数进入指定活动类并要求返回结果
	 * 
	 * @param cls 跳转的活动类
	 * @param bundle 参数
	 * @param requestCode 请求代号
	 */
	public void goActivityAndResult(Class<?> cls, Bundle bundle, int requestCode) {
		Intent intent = new Intent(activity, cls);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		startActivityForResult(intent, requestCode);
	}
	
	/**
	 * 进入指定活动类并要求返回结果
	 * @param cls 跳转的活动类
	 * @param requestCode 请求代号
	 */
	public void goActivityAndResult(Class<?> cls, int requestCode) {
		this.goActivityAndResult(cls, null, requestCode);
	}
	
	//toast处理器
	private static Handler toastHandler = new Handler() {
		
		//处理信息
		public void handleMessage(android.os.Message msg) {
			//发送toast
			Toast.makeText(context,  msg.obj.toString(),
					Toast.LENGTH_SHORT).show();
		};
	};
	
	/**
	 * 调用toastHandler弹出toast
	 * @param text toast的信息
	 */
	public void toastHandler(String text) {
		toastHandler.obtainMessage(0, text).sendToTarget();
	}
	
	/**
	 * 共同的返回列表视图
	 * @return	列表视图
	 */
	public ListView getListView() {
		return listView;
	}
	
	public abstract boolean onKeyBack();
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		this.menu = menu;
	}
	
}
